package com.ljx.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljx.common.ResponseResult;
import com.ljx.domain.dto.AddArticleDto;
import com.ljx.domain.entity.Article;
import com.ljx.domain.entity.ArticleTag;
import com.ljx.domain.entity.Category;
import com.ljx.domain.vo.*;
import com.ljx.loginConfig.RedisCache;
import com.ljx.mapper.ArticleMapper;
import com.ljx.service.ArticleService;
import com.ljx.service.ArticleTagService;
import com.ljx.service.CategoryService;
import com.ljx.utils.BeanCopyUtils;
import com.ljx.utils.SystemConstants;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author 李捷禧
 * Date: 2023/4/18
 * ClassName: ArticleServiceImpl
 */

@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ArticleTagService articleTagService;


    @Override
    public ResponseResult hotArticleList() {

        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        //正式发布的文章
        queryWrapper.eq(Article::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL);
        //根据浏览量进行排序
        queryWrapper.orderByDesc(Article::getViewCount);
        //最多只查询前面十条记录
        Page<Article> page = new Page(1, 10);
        page(page,queryWrapper);
        List<Article> records = page.getRecords();
        //使用stream流转为vo类型
        List<HotArticleVo> hotArticleVos = records.stream().map(article -> {
            HotArticleVo hotArticleVo = new HotArticleVo();
            Integer viewCount = redisCache.getCacheMapValue("article:viewCount", article.getId().toString());
            article.setViewCount(viewCount.longValue());
            BeanUtils.copyProperties(article, hotArticleVo);
            return hotArticleVo;
        }).collect(Collectors.toList());
        return ResponseResult.okResult(hotArticleVos);
    }

    @Override
    public ResponseResult articleList(Integer pageNum, Integer pageSize, Long categoryId) {
        LambdaQueryWrapper<Article> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //分类的id不为空，且大于零
        lambdaQueryWrapper.eq(Objects.nonNull(categoryId)&&categoryId>0,
                Article::getCategoryId,categoryId);
        lambdaQueryWrapper.eq(Article::getStatus,SystemConstants.ARTICLE_STATUS_NORMAL);
        //根据是否置顶来排序
        lambdaQueryWrapper.orderByDesc(Article::getIsTop);
        Page<Article> page = new Page<>(pageNum, pageSize);
        page(page,lambdaQueryWrapper);
        List<Article> articles = page.getRecords();

        for (Article article : articles) {
            Category category = categoryService.getById(article.getCategoryId());
            article.setCategoryName(category.getName());
            Integer viewCount = redisCache.getCacheMapValue("article:viewCount", article.getId().toString());
            article.setViewCount(viewCount.longValue());

        }
//        articles.stream()
//                .map(article ->
//                        article.setCategoryName(categoryService.getById(article.getCategoryId()).getName()))
//                .collect(Collectors.toList());
        //封装查询结果
        List<ArticleListVo> articleListVos = BeanCopyUtils.copyBeanList(page.getRecords(), ArticleListVo.class);

        PageVo pageVo = new PageVo(articleListVos,page.getTotal());
        return ResponseResult.okResult(pageVo);
    }

    @Override
    public ResponseResult getArticleDetail(Long id) {
        Article article = getById(id);
        Integer viewCount = redisCache.getCacheMapValue("article:viewCount", id.toString());
        article.setViewCount(viewCount.longValue());
        ArticleDetailVo articleDetailVo = new ArticleDetailVo();
        BeanUtils.copyProperties(article,articleDetailVo);
        Long categoryId = articleDetailVo.getCategoryId();
        Category category = categoryService.getById(categoryId);
        if(category != null){
            articleDetailVo.setCategoryName(category.getName());
        }
        return ResponseResult.okResult(articleDetailVo);
    }

    @Override
    public ResponseResult updateViewCount(Long id) {
        //更新redis中对应 id的浏览量
        redisCache.incrementCacheMapValue("article:viewCount",id.toString(),1);
        return ResponseResult.okResult();
    }

    @Override
    @Transactional
    public ResponseResult add(AddArticleDto articleDto) {
        //添加 博客
        Article article = BeanCopyUtils.copyBean(articleDto, Article.class);
        save(article);

        HashMap<String, Integer> viewCountMap = new HashMap<>();
        viewCountMap.put(article.getId().toString(),0);
        redisCache.setCacheMap("article:viewCount",viewCountMap);

        List<ArticleTag> articleTags = articleDto.getTags().stream()
                .map(tagId -> new ArticleTag(article.getId(), tagId))
                .collect(Collectors.toList());

        //添加 博客和标签的关联
        articleTagService.saveBatch(articleTags);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult articleAll(Integer pageNum, Integer pageSize, String title, String summary) {
        LambdaQueryWrapper<Article> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(StringUtils.hasText(title),Article::getTitle,title);
        lambdaQueryWrapper.like(StringUtils.hasText(summary),Article::getSummary,summary);
        lambdaQueryWrapper.eq(Article::getStatus,SystemConstants.ARTICLE_STATUS_NORMAL);
        //根据是否置顶来排序
        lambdaQueryWrapper.orderByDesc(Article::getIsTop);
        Page<Article> page = new Page<>(pageNum, pageSize);
        page(page,lambdaQueryWrapper);
        PageVo pageVo = new PageVo(page.getRecords(), page.getTotal());
        return ResponseResult.okResult(pageVo);
    }

    @Override
    public Map<String, Object> findCount(Long create_by, String startDate, String endDate) {
        List<ArticleCountVo> articleCountVos = baseMapper.findCount(create_by,startDate,endDate);
        List<Integer> countList = articleCountVos.stream()
                .map(ArticleCountVo::getArticleCount).collect(Collectors.toList());
        List<String> timeList = articleCountVos.stream()
                .map(ArticleCountVo::getJoinTime).collect(Collectors.toList());
        HashMap<String, Object> map = new HashMap<>();
        map.put("xData",timeList);
        map.put("yData",countList);
        return map;
    }


}
